<template>
  <div class="role-permission-page">
    <el-row>
      <!-- 左侧角色列表 -->
      <el-col :span="6" class="role-list">
        <el-card shadow="always">
          <h3>角色列表</h3>
          <el-table
            :data="roles"
            highlight-current-row
            @current-change="handleRoleSelect"
          >
            <el-table-column prop="name" label="角色名称" />
            <el-table-column prop="description" label="描述" />
          </el-table>
        </el-card>
      </el-col>

      <!-- 右侧多级菜单 + 权限 -->
      <el-col :span="18" style="padding-left:32px;">
      <div class="permission-tree">
        <MenuItem
        v-for="menu in menuTree"
        :key="menu.id"
        :menu="menu"
        :level="0"
        :checkedMenuIds="checkedMenuIds"
        :checkedPermissionMap="checkedPermissionMap"
        @update:checkedMenuIds="val => checkedMenuIds = val"
        @update:checkedPermissionMap="val => checkedPermissionMap = val"
      />
      </div>
      <div style="margin-top:16px;">
          <el-button type="primary" @click="savePermissions">保存权限</el-button>
        </div>
      </el-col>

    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, defineComponent } from "vue";
import { ElMessage } from "element-plus";
import { getRolesListInfoHandler, getMenuTree,createRolesBindInfoHandler,getRolesBindInfoHandler } from "../../api/roles.js";

import MenuItem from "./MenuItem.vue";
// 左侧角色
const roles = ref([]);
const currentRole = ref(null);
const checkedMenuIds = ref([]);  // 角色绑定的菜单
const checkedPermissionMap = ref({});  // 角色绑定的权限


const getBindPermission =async(roleid)=>{
    try {
        const res = await getRolesBindInfoHandler(roleid)
        if (res?.data?.data) {
          const base64String = res.data.data.queryData;
          const decodedBytes = atob(base64String);
          const uint8Array = new Uint8Array(decodedBytes.split('').map(c => c.charCodeAt(0)));
          const decoder = new TextDecoder("utf-8");
          const decodedString = decoder.decode(uint8Array);
          const playData = JSON.parse(decodedString);
          console.log("===============playData======20250923====",playData)
          checkedMenuIds.value=playData[0].menuIds
          checkedPermissionMap.value=playData[0].permissionMap
          console.log("=========checkedMenuIds=========20250923=======",checkedMenuIds.value)
          console.log("=========checkedPermissionMap=========20250923=======",checkedPermissionMap.value)
        
        }
    
    }
    catch(error){
      console.error(error);
      ElMessage.error("加载角色权限失败");
    
    }


}
// 菜单树
const menuTree = reactive([]);

// 选择角色（暂不处理绑定）
function handleRoleSelect(role) {
  currentRole.value = role;
  menuTree.forEach(clearMenuChecked);
  getBindPermission(role.id)
  
}

// 保存勾选权限
const savePermissions = async () => {
  if (!currentRole.value) {
    ElMessage.warning("请先选择角色");
    return;
  }

  const payload = {
    roleId: currentRole.value.id,
    menuIds: checkedMenuIds.value,
    permissionMap: checkedPermissionMap.value
  };

  console.log("保存权限数据:", payload);

  try {
    await createRolesBindInfoHandler(payload);
    ElMessage.success("权限保存成功！");
  } catch (err) {
    console.error(err);
    ElMessage.error("保存失败，请重试");
  }
};

// 清空勾选状态（递归）
function clearMenuChecked(menu) {
  menu.checked = false;
  menu.permissions?.forEach(p => (p.checked = false));
  menu.children?.forEach(clearMenuChecked);
}

// 初始化勾选状态
function initMenuChecked(menu) {
  menu.checked = false;
  menu.permissions?.forEach(p => (p.checked = false));
  menu.children?.forEach(initMenuChecked);
}

// 页面初始化加载
async function loadConfig() {
  try {
    const res = await getRolesListInfoHandler();
    if (res?.data?.data) {
      const base64String = res.data.data.queryData;
      const decodedBytes = atob(base64String);
      const uint8Array = new Uint8Array(decodedBytes.split('').map(c => c.charCodeAt(0)));
      const decoder = new TextDecoder("utf-8");
      const decodedString = decoder.decode(uint8Array);
      roles.value = JSON.parse(decodedString);
    }
  } catch (err) {
    console.error(err);
    ElMessage.error("加载角色失败");
  }
}

async function loadMenuTree() {
  try {
    const res = await getMenuTree();
    if (res?.data?.data) {
      const base64String = res.data.data.menusTree;
      const decodedBytes = atob(base64String);
      const uint8Array = new Uint8Array(decodedBytes.split('').map(c => c.charCodeAt(0)));
      const decoder = new TextDecoder("utf-8");
      const decodedString = decoder.decode(uint8Array);
      const decodedData = JSON.parse(decodedString);

      menuTree.splice(0, menuTree.length, ...decodedData);
      menuTree.forEach(initMenuChecked);
      console.log("++++++++++++++++++++++20250923------------------menuTree",menuTree)
    }
  } catch (err) {
    console.error(err);
    ElMessage.error("加载菜单失败");
  }
}

// 页面加载
onMounted(async () => {
  await loadConfig();
  await loadMenuTree();
  // await getBindPermission(1);
});
</script>
<style scoped>

.roles-permission {
  display: flex;
  gap: 60px; /* 左右拉开距离 */
}
.left-panel {
  width: 250px;
}
.right-panel {
  flex: 1;
  border-left: 1px solid #ddd;
  padding-left: 20px;
}
</style>
